package com.toweave.starter.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;

import com.toweave.starter.R;
import com.toweave.starter.utils.SystemUtil;

public class EditViewActivity extends AppCompatActivity implements View.OnClickListener, View.OnFocusChangeListener {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit_view);

    EditText et_username = findViewById(R.id.et_username);
    et_username.setOnClickListener(this);
    et_username.setOnFocusChangeListener(this);
    et_username.addTextChangedListener(new HideTextWatcher(et_username, 11));

    EditText et_password = findViewById(R.id.et_password);
    et_password.setOnClickListener(this);
    et_password.addTextChangedListener(new HideTextWatcher(et_password, 6));


    EditText et_other = findViewById(R.id.et_other);
    et_other.setOnClickListener(this);
  }

  @Override
  public void onClick(View v) {

  }

  @Override
  public void onFocusChange(View v, boolean hasFocus) {

  }

  private class HideTextWatcher implements TextWatcher {
    private EditText mEditText;
    private int mMaxLength;
    public HideTextWatcher(EditText et, int maxLength) {
      this.mEditText = et;
      this.mMaxLength = maxLength;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
      String str = s.toString();
      // 先去掉监听器，否则会出现栈溢出
      mEditText.removeTextChangedListener(this);
      // 注意这里只能每次都对整个EditText的内容求长度，不能对删除的单个字符求长度
      if (str.length() == mMaxLength ) {
        // 隐藏输入法软件盘
        SystemUtil.hideSoftInputFromWindow(EditViewActivity.this, mEditText);
      }
      mEditText.setText(s);
      mEditText.setSelection(s.length());
      // 恢复监听器
      mEditText.addTextChangedListener(this);
    }
  }
}